package cn.com.dashihui.api.ITask.kit;

import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XmlUtils
{
  public static String getNode(String plain, String nodename)
  {
    if (plain.indexOf("<" + nodename + ">") < 0)
      return "";
    return plain.substring(plain.indexOf("<" + nodename + ">") + nodename.length() + 2, plain.indexOf("</" + nodename + ">"));
  }

  public static Document getDocument(String xml)
  {
    if ((xml == null) || (xml.indexOf("<?xml") < 0))
      return null;
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new ByteArrayInputStream(xml.getBytes()));
      return doc;
    } catch (Exception e) {
      e.printStackTrace();
    }return null;
  }

  public static String getNodeValue(Document doc, String tagname)
  {
    if (doc != null) {
      return ((Element)doc.getElementsByTagName(tagname).item(0)).getFirstChild().getNodeValue();
    }
    return "";
  }
}